$(function() {
	// !Link Table Popup
	// ##### START Modal Related-Data Picker ########
	//When you click on a link with class of poplight and the href starts with a # 
	$('.poplight').click(function() {
	    var fullPopID = $(this).attr('id'); //Get Popup Name
			var brokenPopID = fullPopID.split("_");
			popID = 'popup'+brokenPopID[1];
			
			var selectorData = {
				id: parent_id,
				linkTableName: $(this).closest('.linkedTable').attr('id'),
				childTableName: jsTableName
			};
			//log(selectorData);
			//Make the ajax call to populate the box
			$.ajax({
			   type: "GET",
			   url: jsTableName+"_selector.php",
			   data: selectorData,
			   success: function(r){
				 	//log(r);
			   	$('#'+popID).html(r);
				 }
			 });
			
	    //Fade in the Popup and add close button
	    $('#' + popID).show().css({ 'width': 750 }).prepend('<a href="#" class="close"><img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
	
	    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
	    var popMargTop = ($('#' + popID).height() + 80) / 2;
	    var popMargLeft = ($('#' + popID).width() + 80) / 2;
	
	    //Apply Margin to Popup
	    $('#' + popID).css({
	        'margin-top' : -popMargTop,
	        'margin-left' : -popMargLeft
	    });
	
	    //Fade in Background
	    $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
	    $('#fade').css({'filter' : 'alpha(opacity=80)'}).show(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
	
	    return false;
	});
	
	//Close Popups and Fade Layer
	$('a.close, #fade, .cancelSelection').live('click', function() { //When clicking on the close or fade layer...
	    $('#fade , .popup_block').hide(function() {
	        $('#fade, a.close').remove();  //fade them both out
	    });
	    return false;
	});
	
	$('.selectorRecord').live('click', function() {
		$(this).toggleClass('selected');
		return false;
	});
	
	// Save selection
	$('.saveSelection').live('click', function () {
		var ajaxData = {
			AJAXtask: 'linkTableInsert',
			child_ids: new Array(),
			parentId: parent_id,
			linkTableName: $(this).closest('.linkedTable').attr('id')
		};
		var linkedTable = $(this).closest('.linkedTable');
	
		$(this).closest('.popup_block').find('.selected').each( function () {
			ajaxData.child_ids.push($(this).attr('id'));
		});
		$('.selected').removeClass('selected');
		console.log(ajaxData);
		$.ajax({
		   type: "GET",
		   url: "ajax.php",
		   data: ajaxData,
		   success: function(msg){
		     //log( "Data Saved: " + msg ); 
				 var linkTableData = {
				 		childTableName: child_tablename,
				 		parentId: parent_id,
				 		linkTableName: link_tablename
				 };
		     $.ajax({
		     	 type: "GET",
		     	 data: linkTableData,
				   url: jsTableName+"_linkedtablelist.php",
				   success: function(html){
				   		//log(linkedTable);
							linkedTable.find('.linkedTableList').replaceWith('<div class="linkedTableList sortable">'+html+'</div>');
							
							$('#'+link_tablename+' .sortable').sortable({ 
									items: '.backListRecord',
									handle: '.dragIcon',
									update: function() {
										var orderString = '';
										var order = $('#'+link_tablename+' .sortable').sortable('toArray');
										for (i=0;i<order.length;i++) {
											if (i != 0) { 
												orderString = orderString + '&'; 
											}
											orderString = orderString + 'order[]='+order[i];
										}
										$.ajax({
											type: 'GET',
											url: 'ajax.php',
											data: 'AJAXtask=linksortorderUpdate&link_tablename='+link_tablename+'&parentTable='+jsTableName+'&parent_recordID='+parent_id+'&tablename='+child_tablename+'&'+orderString,
											success: function(msg){
												//alert( \'Data Saved: \' + msg );
											}
										});	
									}
								}); // end sortable
	
				   }
		     }); //end inner ajax
		   }
		 }); //end outer ajax
	
	  $('#fade , .popup_block').hide(function() {
	      $('#fade, a.close').remove();  //fade them both out
	  });
		return false;
	});
	// ##### END Modal Related-Data Picker ########
});